package com.weilele.mvvm.utils.glide;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

public class OkHttpProgressResponseBody extends ResponseBody {
    //OkHttpLoadImage中传进来的response
    private final ResponseBody responseBody;
    private String url;
    private BufferedSource bufferedSource;

    public OkHttpProgressResponseBody(Response response, String url) {
        this.responseBody = response.body();
        this.url = url;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @NotNull
    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(BufferedSource source) {
        return new ForwardingSource(source) {
            long totalBytes = 0L;

            @Override
            public long read(@NotNull Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                // read() returns the number of bytes read, or -1 if this source is exhausted.
                totalBytes += bytesRead != -1 ? bytesRead : 0;
                if (listener != null) {
                    //注意这块的 1.0 *  , 要不两个long除法会一直是 0 
                    listener.update(url, (float) 1.0 * totalBytes / contentLength());
                }
                return bytesRead;
            }
        };
    }

    private OnResponseListener listener;

    public void addOnResponseListener(OnResponseListener listener) {
        this.listener = listener;
    }

    public interface OnResponseListener {
        void update(String key, float progress);
    }
}
